package com.qili.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseDict;
import com.qili.entity.it.FileCollect;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.mapper.it.FileCollectMapper;
import com.qili.mapper.it.ItFileMapper;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseDictService;
import com.qili.service.it.FormBaseService;
import com.qili.service.it.ItFileService;
import com.qili.service.it.ItIndexService;
import com.qili.util.*;
import lombok.extern.java.Log;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liuyang
 * @date 2021/3/18
 * @description IT知识库文件详情相关处理
 */
@Log
@Controller
@RequestMapping("/it/file")
public class ItFileController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    ItIndexService itIndexService;
    @Autowired
    BaseDictService baseDicService;
    @Autowired
    ItFileService itFileService;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    SysUserService userService;
    @Autowired
    FileCollectMapper fileCollectMapper;
    @Autowired
    ItFileMapper itFileMapper;
    @Autowired
    DicDetailController dicDetailController;
    @Autowired
    @Qualifier("FormBaseService")
    FormBaseService formBaseService;

    List<String> fileIds=new ArrayList<>();
    /**
     * 点击文件跳转详情页面
     * @param
     * @return
     */
    @RequestMapping("/particulars")
    public String particulars(Model model, SupervisorFile itFile) {
        SupervisorFile supervisorFile = itFileMapper.selParticulars(itFile);
        if(null == supervisorFile){
            throw new RuntimeException("该文件已经不存在");
        }
        //查看是否收藏了
        boolean ifCollec = itFileService.checkIfCollec(itFile.getId(),CommonUtil.getUserId());
        supervisorFile.setFileCollect(ifCollec ? "1" : "0");
        supervisorFile.setFileNumber(supervisorFile.getId().toUpperCase());
        //文件相关信息
//        System.err.println("文件名："+supervisorFile.getFileName()+"文件id:"+supervisorFile.getId());
        List<SupervisorFile> file =new ArrayList<>();
        if (!StringUtils.isBlank(supervisorFile.getSearchKey())) {
            String searchKey = supervisorFile.getSearchKey();
            String id = supervisorFile.getId();
            file = related(searchKey, id);
        }
        //相关文档前端判断1有数据0没有数据
        if(file.size()>0){
            model.addAttribute("state", "1");
            model.addAttribute("file", file);
        }else{
            model.addAttribute("state", "0");
        }
        //判断是否为项目文件并且是否有权限
        String qx=downloadQx(supervisorFile.getId());
        model.addAttribute("qx",qx);
        String page = "";
        String type ="";
        if (!StringUtils.isBlank(supervisorFile.getFileType())){
            type = itFileService.getFileTypeByFileName(supervisorFile.getFileType());
        }else{
            String fileName = supervisorFile.getFileName();
            if(StringUtils.isNotBlank(fileName) && fileName.contains(".")){
                type = itFileService.getFileTypeByFileName(fileName);
            }
        }
        //文档和图片、视频不同页面
        if("1".equals(type)||"2".equals(type)){
            String imgUrl = supervisorFile.getUrl();
            model.addAttribute("type",type);
            model.addAttribute("imgUrl",url(imgUrl));
            page = "itDetail";
        }else{
            page = "itDetail1";
        }
        //判断文件所在文件夹是否是表单文件夹:
        String fileFormAbout = dicDetailController.getFileFormAbout(itFile.getId());
        if("2".equals(fileFormAbout)){
            String formCenterFileId = formBaseService.getFormCenterFileId(itFile.getId());
            if(StringUtils.isNotBlank(formCenterFileId)){
                model.addAttribute("formCenterFileId",formCenterFileId);
            }else{
                log.warning("表单下的文件夹("+itFile.getId()+"),未找到其表单核心文件夹!");
            }
        }
        model.addAttribute("fileIsForm",fileFormAbout);
        if("1".equals(fileFormAbout)){
            List<BaseDict> formFileDictList = DictUtil.getDictByType(DictTypes.FORMFILE);
            List<BaseDict> boys = formFileDictList.stream().filter(s-> s.getBadtCode().equals(itFile.getId())).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(boys)){
                model.addAttribute("formTypeCode",boys.get(0).getBadtGroupid());
            }
        }
        //截取文件路径
        if(StringUtils.isNotBlank(supervisorFile.getUrl())){
            String uploadPath = uploadUtil.getUploadPath();
            model.addAttribute("thisFilePath",supervisorFile.getUrl().substring(uploadUtil.getUploadPath().length()-1));

        }
        model.addAttribute("selectFile",supervisorFile);
        return page;
    }

    //下载时权限控制
    @RequestMapping("/jurisdiction")
    @ResponseBody
    public JsonUtil jurisdiction(String id){
        JsonUtil json=new JsonUtil();
        Map map=new HashMap();
        map.put("id",id);
        map.put("download", CommonUtil.getUserRoleList());
        List<SupervisorFile> list=itIndexService.selectItFile(map);
        if (list.size()>0) {
            json.setMsg("下载成功");
            json.setFlag(true);
            return json;
        }else{
            json.setMsg("您没有权限下载");
            json.setFlag(false);
            return json;
        }
    }
    //检索弹框
    @GetMapping("/searching")
    @RequiresPermissions("it:searching")
    public String searching(Model model,SupervisorFile file){
        SupervisorFile itf=itIndexService.selectOne(file);
        model.addAttribute("itf",itf);
        return "/add_searching";
    }
    /**
     * 检索设置
     * @param file
     * @return
     */
    @PostMapping("/searchingFile")
    @ResponseBody
    public JsonUtil searchingFile(SupervisorFile file){
        JsonUtil json=new JsonUtil();
        if(itIndexService.updateByPrimaryKeySelective(file)>0){
            json.setMsg("检索设置成功");
            json.setFlag(true);
            return json;
        }else{
            json.setMsg("检索设置失败");
            json.setFlag(false);
            return json;
        }
    }
    /**
     * 删除
     * @param file
     * @return
     */
    @PostMapping("/deleteFile")
    @ResponseBody
    public JsonUtil deleteFile(SupervisorFile file){
        String time=DateUtil.getCurrentDateTimeString();
        file.setDeleteDate(time);
        String userId=CommonUtil.getUserId();
        file.setDeleteUser(userId);
        JsonUtil json=new JsonUtil();
        if(itIndexService.updateByPrimaryKeySelective(file)>0){
            json.setMsg("删除成功");
            json.setFlag(true);
        }else{
            json.setMsg("删除失败");
            json.setFlag(false);
        }
        return json;
    }

    /**
     * 彻底删除
     * @param ids
     * @return
     */
    @PostMapping("/inGrainDel")
    @ResponseBody
    public JsonUtil inGrainDel(String ids){
        JsonUtil json=new JsonUtil();
        String [] arr=ids.split(",");
        SupervisorFile supFile=new SupervisorFile();
        List<String>list =new ArrayList<>();
        for(int i=0;i<arr.length;i++){
            supFile=itFileService.selectByPrimaryKey(arr[i]);
            if(supFile!=null && StringUtils.isNotBlank(supFile.getUrl())){
                File oldFile = new File(supFile.getUrl());
                del(oldFile);
                fileIds.add(arr[i]);
                list = sel(arr[i]);
                for(String l:list){
                    itFileService.deleteByPrimaryKey(l);
                }
            }
        }
        fileIds.clear();
        json.setMsg("删除成功");
        json.setFlag(true);
        return json;
    }
    /**
     * 清空回收站
     * @return
     */
    @PostMapping("/empty")
    @ResponseBody
    public JsonUtil empty(){
        JsonUtil json=new JsonUtil();
        Map map =new HashMap();
        List<SupervisorFile> sufile=itFileService.selectDelete(map);
        SupervisorFile supFile=new SupervisorFile();
        List<String>list =new ArrayList<>();
        for(SupervisorFile file:sufile){
            supFile=itFileService.selectByPrimaryKey(file.getId());
            if(supFile!=null||!StringUtils.isBlank(supFile.getUrl())){
                File oldFile = new File(supFile.getUrl());
                del(oldFile);
                fileIds.add(file.getId());
                list = sel(file.getId());
                for(String l:list){
                    itFileService.deleteByPrimaryKey(l);
                }
            }
        }
        fileIds.clear();
        json.setMsg("清空成功");
        json.setFlag(true);
        return json;
    }
    //查出下级所有id
    public List<String> sel(String id){
        SupervisorFile delFile = new SupervisorFile();
        delFile.setSuperiorId(id);
        List<SupervisorFile> file=itFileService.select(delFile);
        if(file.size()>0){
            for (SupervisorFile f:file){
                fileIds.add(f.getId());
                sel(f.getId());
            }
        }
        return fileIds;
    }
    //删除磁盘真实文件
    public void del(File file){
        boolean directory = file.isDirectory();
        if(directory){
            File[] files = file.listFiles();
            if(files.length>0){
                for(File aFile : files){
                    if(aFile.isFile()){
                        aFile.delete();
                    }else{
                        del(aFile);
                    }
                }
                file.delete();
            }else{
                file.delete();
            }
        }else{
            file.delete();
        }
    }
    /**
     * 文件回收站还原
     * @param fileId
     * @return
     */
    @PostMapping("/restore")
    @ResponseBody
    public JsonUtil restore(String fileId){
        JsonUtil json=new JsonUtil();
        String [] arr=fileId.split(",");
        for(int i=0;i<arr.length;i++){
            SupervisorFile down=itFileService.selectByPrimaryKey(arr[i]);
            if(!StringUtils.isBlank(down.getSuperiorId())){
                int state=upRestore(down.getSuperiorId());
                if(state==0){
                    json.setMsg("上级文件夹还原失败");
                    json.setFlag(false);
                    return json;
                }
            }
            int a=updatefile(arr[i],"1");
            if(a<0){
                json.setMsg("还原失败");
                json.setFlag(false);
                return json;
            }
        }
        json.setMsg("还原成功");
        json.setFlag(true);
        return json;
    }
    //查询并还原上级文件夹
    public int upRestore(String id){
        SupervisorFile down=itFileService.selectByPrimaryKey(id);
        if(down!=null&&"2".equals(down.getDeleteState())&&!StringUtils.isBlank(down.getSuperiorId())){
            int i=updatefile(down.getId(),"1");
            if(i>0){
               return upRestore(down.getSuperiorId());
            }
        }
        return 1;
    }
    public int updatefile(String id,String state){
        SupervisorFile files=new SupervisorFile();
        files.setId(id);
        files.setDeleteState(state);
        return itFileService.updateByPrimaryKeySelective(files);
    }

    //文档详情页查询相关文档
    public List<SupervisorFile> related(String searchKey,String id){
        List<SupervisorFile> itfile=new ArrayList<>();
//        String name=fileName.substring(0,fileName.indexOf("."));
        Map map=new HashMap();
        map.put("examine",CommonUtil.getUserRoleList());
        map.put("searchKey",searchKey);
        map.put("limit",3);
        map.put("id",id);
        List<SupervisorFile> file=itFileService.selectRelated(map);
        for(SupervisorFile file1:file){
            if(!id.equals(file1.getId())){
                String fileType = "";
                if(StringUtils.isNotBlank(file1.getFileType())){
                    fileType = itFileService.getFileTypeByFileName(file1.getFileType());
                }else{
                    String fileName = file1.getFileName();
                    if(StringUtils.isNotBlank(fileName) && (fileName.indexOf(".") != -1)){
                        fileType = itFileService.getFileTypeByFileName(fileName);
                    }
                }
                if("1".equals(fileType)||"2".equals(fileType)){
                    String url=url(file1.getUrl());
                    file1.setUrl(url);
                }
                itfile.add(file1);
            }
        }
        return itfile;
    }
    //图片的url
    public String url(String url){
        String imgUrl = url;
        String uploadPath = uploadUtil.getUploadPath();
        imgUrl = imgUrl.substring(uploadPath.length());
        imgUrl = File.separator+"itfile"+File.separator+imgUrl;
        return imgUrl;
    }

    //替换
    @RequestMapping(value = "/replace", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil replace(@RequestParam(value = "file", required = false) MultipartFile filedata, SupervisorFile file) {
        String userId = CommonUtil.getUserId();
        if(StringUtils.isBlank(file.getId())){
            return JsonUtil.error("参数错误");
        }
        String fileName=filedata.getOriginalFilename();
        String fileTypeByFileName = itFileService.getFileTypeByFileName(fileName);
        if(!"1".equals(fileTypeByFileName)){
            return JsonUtil.error("请上传图片");
        }
        SupervisorFile oldFile = itFileService.selectByPrimaryKey(file.getId());
        String dicId = oldFile.getSuperiorId();
        SupervisorFile dicFile = itFileService.selectByPrimaryKey(dicId);
        if(null == dicFile || StringUtils.isBlank(dicFile.getUrl())){
            return JsonUtil.error("所在目录路径为空");
        }
        String dicPath = dicFile.getUrl();
        String newFilePath = dicPath.endsWith(File.separator) ? dicPath + fileName : dicPath + File.separator + fileName;
        File newFile = new File(newFilePath);
        if(newFile.exists()){
            return JsonUtil.error("已经存在的文件名称");
        }
        //保存文件
        try {
            FileUtils.copyInputStreamToFile(filedata.getInputStream(), newFile);
            SupervisorFile newSFile = new SupervisorFile();
            newSFile.setId(oldFile.getId());
            newSFile.setUrl(newFile.getPath());
            newSFile.setFileName(fileName);
            String type=fileName.substring(fileName.lastIndexOf('.'));
            newSFile.setFileType(type);
            int i=itFileService.updateByPrimaryKeySelective(newSFile);
            if(i>0){
                File oldFileOS = new File(oldFile.getUrl());
                if(oldFileOS.exists()){
                    oldFileOS.delete();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return JsonUtil.error("替换失败");
        }
        return JsonUtil.sucess("替换成功");
    }

    //判断文件是哪个格式
    public String format(String file){
        file=file.substring(file.indexOf('.')+1,file.length());
        if("jpg".equals(file)||"png".equals(file)||"gif".equals(file)||"jpeg".equals(file)||"psd".equals(file)||"bmp".equals(file)){
            return "1";
        }else if("mp4".equals(file)||"avi".equals(file)||"wmv".equals(file)||"mpg".equals(file)||"rm".equals(file)||"swf".equals(file)||"mpeg".equals(file)){
            return "2";
        }else{
            return "3";
        }
    }

    /**
     * 回收站页面跳转
     * @return
     */
    @RequestMapping("/recycle")
    public String recycle(){
        return "recycleBin";
    }
    /**
     * 查询回收站
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/selectDel")
    @ResponseBody
    public ReType SelectDel(Integer page,Integer limit){
        Page<SupervisorFile> tPage = PageHelper.startPage(page, limit);
        Map map=new HashMap();
        List<SupervisorFile> sufile=itFileService.selectDelete(map);
        return new ReType(tPage.getTotal(), sufile);
    }

    /**
     *文件的收藏或取消
     * @param state
     * @param id
     * @return
     */
    @RequestMapping("fileCollect")
    @ResponseBody
    public JsonUtil fileCollect(String state,String id){
        JsonUtil json=new JsonUtil();
        String userId = CommonUtil.getUserId();
        FileCollect filecol=new FileCollect();
        filecol.setFileId(id);
        filecol.setUserId(userId);
        if("1".equals(state)){
            if(fileCollectMapper.delete(filecol)>0){
                json.setFlag(true);
                json.setMsg("取消成功");
                return json;
            }
        }else if("0".equals(state)){
            filecol.setId(IdUtil.simpleUUID());
            filecol.setCreationTime(DateUtil.getCurrentDateTimeString());
            if(fileCollectMapper.insertSelective(filecol)>0) {
                json.setFlag(true);
                json.setMsg("收藏成功");
                return json;
            }
        }
        json.setFlag(false);
        json.setMsg("错误");
        return json;
    }

    //项目相关文件下载权限 1：有下载权限；0：没有下载权限
    public String downloadQx(String id){
        String xmwj=recursion(id);
        if("1".equals(xmwj)){
            return "1";
        }else if("0".equals(xmwj)){
            boolean b = itIndexService.canIDownload(id);
            if(b){
                return "1";
            }else{
                return "0";
            }
        }
        return "0";
    }
    //递归判断是否是项目文件 1:项目文件有权限；2：项目文件没权限；0：不是项目文件
    public String recursion(String id){
        SupervisorFile file= itFileService.selectByPrimaryKey(id);
        if(null!=file&&!"".equals(file)){
            int i=qx(file.getId());
            if(i==1){
                return "1";
            }else if(i==2){
                return "2";
            }else if(i==0&&!StringUtils.isBlank(file.getSuperiorId())){
                return recursion(file.getSuperiorId());
            }else if(i==0&&StringUtils.isBlank(file.getSuperiorId())){
                return "0";
            }
        }
        return "1";
    }
    //传入id根据字典查询判断是否有下载权限; 0:没有查到；1：有权限；2：没权限
    public int qx(String id){
        BaseDict wjdict = DictUtil.getDictByCode(DictTypes.XMWJ, id);
        return 0;
//        if(null==wjdict||"".equals(wjdict)){
//            return 0;
//        }else{
//            String level1=wjdict.getBadtCode();
//            List<String> list=CommonUtil.getUserRoleList();
//            int i=0;
//            for(String ls:list){
//                if(level1.indexOf(ls)>0){
//                    i++;
//                }
//            }
//            if(i>0){
//                return 1;
//            }else {
//                return 2;
//            }
//        }
    }

}
